package com.ty.springbootshiro.service.impl;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.springbootshiro.entity.Right;
import com.ty.springbootshiro.entity.Role;
import com.ty.springbootshiro.entity.User;
import com.ty.springbootshiro.mapper.RoleMapper;
import com.ty.springbootshiro.service.RoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * RoleServiceImpl
 *
 * @aurhor whs
 * @since 2024/10/16
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource RoleService roleService;

    /**
     * 权限刷新
     *
     * @return
     */
    public ShiroFilterFactoryBean loadFilterChainDefinitions() {
        ShiroFilterFactoryBean shiroFilterFactory = new ShiroFilterFactoryBean();

        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); // 必须使用LinkedHashMap 有序集合
        // 配置可以匿名访问资源的url： 静态资源
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");

        filterChainDefinitionMap.put("/login/**", "anon");
        filterChainDefinitionMap.put("/logout/**", "anon");  // 注销过滤器 ， 自动注销

//        // 动态授权
        List<Right> rights = roleService.findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl()!=null && right.getRightUrl().trim().equals("")) { // .startsWith("/user/")
                filterChainDefinitionMap.put(right.getRightUrl(), "perms["+right.getRightUrl()+"]");
            }
        }
        // 配置认证访问 ： 其他资源URl必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc");  // 必须放在过滤器链的最后面
        shiroFilterFactory.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return (ShiroFilterFactoryBean) filterChainDefinitionMap;
    }

    /**
     * 重新加载动态权限，配置权限验证规则
     */
    public void reloadFilterChainDefinitions() {
        try {
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext = request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("shiroFilterFactory");

            synchronized (shiroFilter) {
                // 获取过滤器管理
                PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                // 清空初始权限配置
                manager.getFilterChains().clear();
                // 重新加载动态权限 ， 配置权限验证规则
                Map<String, String> chains = (Map<String, String>) loadFilterChainDefinitions();
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();
                    String chainDefinition = entry.getValue().trim().replace(" ", "");
                    manager.createChain(url, chainDefinition);
                }
                System.out.println("更新权限成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Override
    public List<Role> list() {
        return roleMapper.list();
    }

    @Override
    public List<Right> findAllRights() {
        return  roleMapper.findAllRights();
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return roleMapper.findRightsByRole(role);
    }

    @Override
    public Role saveRole(Role role) {
        return roleMapper.saveRole(role);
    }

    @Override
    public void deleteRole(Long roleId) {
        roleMapper.deleteRole(roleId);
    }

    @Override
    public Role getRole(Long roleId) {
        return roleMapper.getRole(roleId);
    }

    @Override
    public Page<Role> rolePage(String roleName, Page<Role> rolePager) {
        return roleMapper.rolePage(roleName, rolePager);
    }

    @Override
    public Role findRoleByUsers(User user) {
        return roleMapper.findRoleByUsers(user);
    }

    @Override
    public List<Role> findAllRoles() {
        return roleMapper.list();
    }
}
